package com.xbongbong.paas.help.menu;/*/*/

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.admin.pojo.dto.MirrorRollBackDTO;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.dao.PaasPrintTemplateDao;
import com.xbongbong.paas.domain.entity.PaasAppEntity;
import com.xbongbong.paas.domain.entity.PaasFormEntity;
import com.xbongbong.paas.domain.entity.PaasMenuEntity;
import com.xbongbong.paas.domain.entity.PaasPrintTemplateEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.OptionalRangeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.help.LowCodeHelp;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.pojo.FormTitlePoJo;
import com.xbongbong.paas.pojo.SummaryDataPoJo;
import com.xbongbong.paas.pojo.dto.FormEntityAddDTO;
import com.xbongbong.paas.pojo.dto.MenuFormAddDTO;
import com.xbongbong.paas.service.PaasMenuService;
import com.xbongbong.paas.service.init.AbstractInitMenuHelp;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.helper.ReflectHelper;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.enums.AccessLinkEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.menu.enums.SystemAppMenuEnum;
import com.xbongbong.pro.enums.menu.enums.WorkOrderMenuEnum;
import com.xbongbong.pro.fundset.pojo.FundSetTransitionPojo;
import com.xbongbong.pro.menu.pojo.dto.MenuFormAddBatchDTO;
import com.xbongbong.pro.menu.pojo.dto.MenuInitDTO;
import com.xbongbong.pro.menu.pojo.vo.MenuFormAddBatchVO;
import com.xbongbong.pro.menu.pojo.vo.MenuInitVO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.domain.entity.WorkOrderExplainEntity;
import com.xbongbong.saas.domain.entity.WorkOrderFormEntity;
import com.xbongbong.saas.domain.entity.WorkOrderTemplateCategoryEntity;
import com.xbongbong.saas.domain.entity.WorkOrderTemplateEntity;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.WorkOrderEnum;
import com.xbongbong.saas.help.LabelHelp;
import com.xbongbong.saas.model.WorkOrderExplainModel;
import com.xbongbong.saas.model.WorkOrderFormModel;
import com.xbongbong.saas.model.WorkOrderTemplateCategoryModel;
import com.xbongbong.saas.model.WorkOrderTemplateModel;
import com.xbongbong.saas.script.help.InitExplainsHelper;
import com.xbongbong.saas.service.WorkOrderTemplateCategoryService;
import com.xbongbong.saas.service.WorkOrderTemplateService;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.UserModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 *
 * @author 魏荣杰
 * @date 2019/3/13 14:25
 * @since v1.0
 * @version v1.0
 */
@Component
public class InitWorkOrderHelp extends AbstractInitMenuHelp{
    private static final Logger LOG = LoggerFactory.getLogger(InitWorkOrderHelp.class);
    @Resource
    private WorkOrderTemplateService workOrderTemplateService;
    @Resource
    private WorkOrderTemplateCategoryService workOrderTemplateCategoryService;
    @Resource
    private WorkOrderTemplateCategoryModel workOrderTemplateCategoryModel;
    @Resource
    private UserModel userModel;
    @Resource
    private WorkOrderExplainModel workOrderExplainModel;
    @Resource
    private WorkOrderFormModel workOrderFormModel;
    @Resource
    private PaasMenuService paasMenuService;
    @Resource
    private WorkOrderTemplateModel workOrderTemplateModel;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private PaasPrintTemplateDao paasPrintTemplateDao;
    @Resource
    private LabelHelp labelHelp;
    @Resource
    private LowCodeHelp lowCodeHelp;


    @Override
    public List<String> alias() {
        return Arrays.asList(SystemAppMenuEnum.WORK_ORDER.getAlias());
    }
    @Override
    public MenuInitVO initApp(MenuInitDTO menuInitDTO, Map<String, PaasAppEntity> appMap) throws XbbException {
        PaasFormEntityExt paasFormEntity = paasFormModel.getByBusinessType(XbbRefTypeEnum.PRODUCT.getCode(),menuInitDTO.getCorpid());
        if (Objects.isNull(paasFormEntity)) {
            paasFormEntity = paasFormModel.getByBusinessTypeNoEnable(XbbRefTypeEnum.PRODUCT.getCode(),menuInitDTO.getCorpid());
        }
        menuInitDTO.setProductForm(paasFormEntity);
        return initMenu(menuInitDTO, appMap);
    }

    @Override
    public MenuInitVO initMenu(MenuInitDTO menuInitDTO, Map<String, PaasAppEntity> appMap) throws XbbException {
        MenuInitVO menuInitVO = new MenuInitVO();
        try {
            // 获取下应用id
            menuInitDTO.setAppId(appMap.get(SystemAppMenuEnum.WORK_ORDER.getAlias()).getId());
            // 插入除分组外对应的菜单
            MenuFormAddBatchVO menuFormAddBatchVO = formAddBatch(menuInitDTO);
            if (Objects.isNull(menuFormAddBatchVO)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
            }
            Map<String, Object> param = new HashMap<>(16);
            param.put("corpid", menuInitDTO.getCorpid());
            param.put("del", 0);
            param.put("appId", menuInitDTO.getAppId());
            Integer count = workOrderTemplateCategoryModel.getEntitysCount(param);
            if (count > 0) {
                //已经存在分类，不用再生成
                return menuInitVO;
            }
            UserEntity userEntity = userModel.getByKey(menuInitDTO.getUserId(), menuInitDTO.getCorpid());
            // 初始化时userEntity可能为空
            if (Objects.equals(menuInitDTO.getCompanyInit(), 1) && userEntity == null) {
                userEntity = new UserEntity();
                userEntity.setCorpid(menuInitDTO.getCorpid());
                userEntity.setUserId("");
                userEntity.setName("");
            }
            //初始化分类
            Long categoryId = workOrderTemplateCategoryService.initTemplateCategory(menuInitDTO, userEntity);
            //初始化模板
            Long templateId = workOrderTemplateService.initTemplate(menuInitDTO, categoryId, userEntity);
            //初始化工单表单
            Long menuId = 0L;
            for (PaasMenuEntity item : menuFormAddBatchVO.getMenuList()) {
                if (Objects.equals(XbbRefTypeEnum.WORK_ORDER.getAlias(), item.getAlias())) {
                    menuId = item.getId();
                    break;
                }
            }
            Long formId = formAdd(menuInitDTO, templateId, menuId);
            PaasFormEntity paasFormEntity = paasFormModel.getByBusinessType(XbbRefTypeEnum.PRODUCT.getCode(),menuInitDTO.getCorpid());
            if (Objects.isNull(paasFormEntity)) {
                paasFormEntity = paasFormModel.getByBusinessTypeNoEnable(XbbRefTypeEnum.PRODUCT.getCode(),menuInitDTO.getCorpid());
            }
            menuInitDTO.setProductForm(paasFormEntity);
            formExplainAdd(menuInitDTO, formId, menuId);
            // 初始化工单打印模板
            initWorkOrderPrintTemplate(menuInitDTO,formId,menuId);
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("InitWorkOrderHelp.initMenu初始化菜单出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return menuInitVO;
    }

    /**
     * 回退工单到初始化
     * @param mirrorRollBackDTO
     * @param installFormList
     * @param productFormEntity 产品实体
     * @throws XbbException
     */
    @Override
    public void rollBackInit(MirrorRollBackDTO mirrorRollBackDTO, List<Long> installFormList, PaasFormEntity productFormEntity) throws XbbException {
        String targetCorpid = mirrorRollBackDTO.getTargetCorpid();
        try {
            // 无法确定人员, 暂定置为空
            UserEntity userEntity = new UserEntity();
            userEntity.setCorpid(targetCorpid);
            userEntity.setUserId("");
            userEntity.setName("");
            Long now = DateTimeUtil.getInt();

            // 1. 回退工单默认分类(只有一个)
            HashMap<String ,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put("corpid", targetCorpid);
            param.put("isDefault", BasicConstant.ONE);
            param.put("del", DelEnum.NORMAL.getDel());
            List<WorkOrderTemplateCategoryEntity> workOrderCategoryList = workOrderTemplateCategoryModel.findEntitys(param);
            WorkOrderTemplateCategoryEntity workOrderCategoryEntity = workOrderCategoryList.get(0);
            workOrderCategoryEntity.setName(I18nMessageUtil.getMessage(I18nStringConstant.DEFAULT_CATEGORY));
            workOrderCategoryEntity.setIsDefault(1);
            workOrderCategoryEntity.setSort(0);
            workOrderCategoryEntity.setCreatorId(userEntity.getUserId());
            workOrderCategoryEntity.setCreatorName(userEntity.getName());
            workOrderCategoryEntity.setModifierId(userEntity.getUserId());
            workOrderCategoryEntity.setModifierName(userEntity.getName());
            workOrderCategoryEntity.setDel(0);
            workOrderTemplateCategoryModel.update(workOrderCategoryEntity);

            // 2. 回退默认模板(查询默认分类下的所有模板, 只覆盖默认模板,其余的删除)
            HashSet<Long> templateIds = new HashSet<>();
            Long defaultTemplateId = 0L;
            param.clear();
            param.put("corpid", targetCorpid);
            param.put("categoryId", workOrderCategoryEntity.getId());
            param.put("del", DelEnum.NORMAL.getDel());
            List<WorkOrderTemplateEntity> workOrderTemplateList = workOrderTemplateModel.findEntity(param);
            for (WorkOrderTemplateEntity entity : workOrderTemplateList) {
                if (Objects.equals(entity.getIsDefault(), BasicConstant.ONE)) {
                    entity.setName(I18nMessageUtil.getMessage(I18nStringConstant.AFTER_SALE));
                    entity.setIntroduction(I18nMessageUtil.getMessage(I18nStringConstant.SYSTEM_DEFAULT_TEMPLATE));
                    entity.setIsFree(1);
                    entity.setCc("[]");
                    entity.setEnable(1);
                    entity.setIsDefault(1);
                    JSONObject scopeRule = new JSONObject();
                    scopeRule.put("inside", 1);
                    scopeRule.put(OptionalRangeEnum.USER.getValue(), new JSONArray());
                    scopeRule.put(OptionalRangeEnum.DEPT.getValue(),new JSONArray());
                    entity.setScopeRule(scopeRule.toJSONString());
                    entity.setCreatorId(userEntity.getUserId());
                    entity.setCreatorName(userEntity.getName());
                    entity.setModifierId(userEntity.getUserId());
                    entity.setModifierName(userEntity.getName());
                    entity.setExpectedTime(0);
                    entity.setDel(0);
                    entity.setUpdateTime(now);
                    defaultTemplateId = entity.getId();
                } else {
                    entity.setDel(DelEnum.DELETE.getDel());
                }
                templateIds.add(entity.getId());
            }
            workOrderTemplateModel.updateBatch(workOrderTemplateList, mirrorRollBackDTO.getTargetCorpid());

            // 3. 回退工单表单
            HashSet<Long> formIds = new HashSet<>();
            Long defaultFormId = 0L;
            param.clear();
            param.put("corpid", targetCorpid);
            param.put("templateIdIn", templateIds);
            param.put("del", DelEnum.NORMAL.getDel());
            List<WorkOrderFormEntity> workOrderFormList = workOrderFormModel.findEntitys(param);
            for (WorkOrderFormEntity entity : workOrderFormList) {
                if (Objects.equals(entity.getTemplateId(), defaultTemplateId)) {
                    defaultFormId=entity.getId();
                    entity.setName(I18nMessageUtil.getMessage(I18nStringConstant.AFTER_SALE));
                    FormEntityAddDTO formEntityAddDTO = new FormEntityAddDTO();
                    entity.setSummary(JSONObject.toJSONString(getWorkOrderDefaultSummary(XbbRefTypeEnum.WORK_ORDER.getCode())));
                    entity.setLabels(JSONObject.toJSONString(getWorkOrderDefaultLabel(XbbRefTypeEnum.WORK_ORDER.getCode())));
                    entity.setAssociationList(JSONObject.toJSONString(formEntityAddDTO.getAssociationList()));
                    entity.setBusinessRules(formEntityAddDTO.getBusinessRules());
                    entity.setCoOpPerms(JSONObject.toJSONString(formEntityAddDTO.getCoOpPerms()));
                    entity.setCustomTitle(JSONObject.toJSONString(getWorkOrderDefaultTitle(XbbRefTypeEnum.WORK_ORDER.getCode())));
                    entity.setCreatorId(userEntity.getUserId());
                    entity.setUpdateTime(now);
                    entity.setDel(0);
                } else {
                    entity.setDel(DelEnum.DELETE.getDel());
                }
                formIds.add(entity.getId());
            }
            workOrderFormModel.updateBatch(workOrderFormList, targetCorpid);

            // 4. 回退工单表单解释
            param.clear();
            param.put("corpid", targetCorpid);
            param.put("formIdIn", formIds);
            param.put("del", DelEnum.NORMAL.getDel());
            List<WorkOrderExplainEntity> workOrderExplainList = workOrderExplainModel.findEntitys(param);
            FundSetTransitionPojo fundSetTransitionPojo = new FundSetTransitionPojo(targetCorpid);
            for (WorkOrderExplainEntity entity : workOrderExplainList) {
                if (Objects.equals(entity.getFormId(), defaultFormId)) {
                    entity.setExplains(JSON.toJSONString(InitExplainsHelper.initFieldAttrEntity(XbbRefTypeEnum.WORK_ORDER.getAlias(), productFormEntity, fundSetTransitionPojo, 0)));
                } else {
                    entity.setDel(DelEnum.DELETE.getDel());
                }
            }
            workOrderExplainModel.updateBatch(workOrderExplainList, targetCorpid);

            /*// 更新应用(待定)
            PaasAppEntity paasAppEntity = paasAppModel.getByKey(mirrorRollBackDTO.getAppId(), mirrorRollBackDTO.getTargetCorpid());
            SystemAppMenuEnum systemAppMenuEnum = SystemAppMenuEnum.getSystemAppMenuEnum(mirrorRollBackDTO.getAlias());
            AccessLinkEnum accessLinkEnum = systemAppMenuEnum.getAccessLinkEnum();
            paasAppEntity.setIcon(accessLinkEnum.getIcon());
            paasAppEntity.setColor(accessLinkEnum.getColor());
            paasAppEntity.setName(systemAppMenuEnum.getName());
            paasAppModel.update(paasAppEntity);*/

            // 工单打印模板新增
            rollBackToDefaultPrintTemplates(targetCorpid, mirrorRollBackDTO.getAppId(), workOrderFormList, defaultFormId);
            // 标签初始化
            List<PaasFormEntity> paasFormEntityList = new ArrayList<>();
            workOrderFormList.forEach(item->{
                PaasFormEntity paasFormEntity = new PaasFormEntity();
                BeanUtil.copyProperties(item, paasFormEntity);
                paasFormEntityList.add(paasFormEntity);
            });
            labelHelp.deleteAllAndinit(paasFormEntityList, targetCorpid, mirrorRollBackDTO.getAppId());

            // 工单初始化时没有低代码，此处删除所有低代码
            lowCodeHelp.deleteLowCode(targetCorpid, formIds, XbbRefTypeEnum.WORK_ORDER.getCode());

        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("InitWorkOrderHelp.initMenu初始化菜单出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
    }

    private void initWorkOrderPrintTemplate(MenuInitDTO menuInitDTO, Long formId, Long menuId) throws XbbException {
        PaasPrintTemplateEntity paasPrintTemplateEntity = new PaasPrintTemplateEntity();
        HashMap<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid","0");
        param.put("del", DelEnum.NORMAL.getDel());
        param.put("businessType", XbbRefTypeEnum.WORK_ORDER.getCode());
        List<PaasPrintTemplateEntity> defaultList = paasPrintTemplateDao.findEntitys(param);
        if (defaultList.isEmpty()) {
            // 数据库中没有存在默认模板配置
            return;
        }
        Long now = DateUtil.getLong();
        PaasPrintTemplateEntity defaultPrintTemplate = defaultList.get(0);
        paasPrintTemplateEntity.setCorpid(menuInitDTO.getCorpid());
        paasPrintTemplateEntity.setAppId(menuInitDTO.getAppId());
        paasPrintTemplateEntity.setMenuId(menuId);
        paasPrintTemplateEntity.setFormId(formId);
        paasPrintTemplateEntity.setName(defaultPrintTemplate.getName());
        paasPrintTemplateEntity.setEnable(defaultPrintTemplate.getEnable());
        paasPrintTemplateEntity.setHtml(defaultPrintTemplate.getHtml());
        paasPrintTemplateEntity.setConfigInfo(defaultPrintTemplate.getConfigInfo());
        paasPrintTemplateEntity.setBusinessType(defaultPrintTemplate.getBusinessType());
        paasPrintTemplateEntity.setCreatorId(menuInitDTO.getUserId());
        paasPrintTemplateEntity.setAddTime(now);
        paasPrintTemplateEntity.setUpdateTime(now);
        try {
            paasPrintTemplateDao.insert(paasPrintTemplateEntity);
        } catch (Exception e) {
            LOG.error("工单生成默认打印模板出错");
            throw  new XbbException(SystemErrorCodeEnum.API_ERROR_100001 ,SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
    }


    /**
     * 初始化，为公司saas模块增加默认打印模板
     * @param  corpid
     * @param  appId
     * @param formList 表单列表
     */
    private void rollBackToDefaultPrintTemplates(String corpid,Long appId, List<WorkOrderFormEntity> formList,Long defaultFormId) throws XbbException {
        try {
            HashSet<Long> selectFormIds = new HashSet<>();
            Long menuId = 0L;
            for (WorkOrderFormEntity item : formList) {
                selectFormIds.add(item.getId());
                if (menuId == 0L) {
                    menuId = item.getMenuId();
                }
            }
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put("columns", " id , name");
            param.put("corpid", corpid);
            param.put("appId", appId);
            param.put("formIdIn", selectFormIds);
            param.put("del", DelEnum.NORMAL.getDel());
            List<PaasPrintTemplateEntity> printTemplateEntities = paasPrintTemplateDao.findEntitys(param);
            List<Long> delIds = new ArrayList<>();
            printTemplateEntities.forEach(item -> delIds.add(item.getId()));
            if (delIds.size() > 0) {
                paasPrintTemplateDao.deleteBatch(delIds, corpid);
            }
            // 查询默认打印模板
            param.clear();
            param.put("corpid", "0");
            param.put("businessType", XbbRefTypeEnum.WORK_ORDER.getCode());
            param.put("del", DelEnum.NORMAL.getDel());
            List<PaasPrintTemplateEntity> defaultList = paasPrintTemplateDao.findEntitys(param);
            if (CollectionsUtil.isEmpty(defaultList)) {
                // 数据库中没有存在默认模板配置
                return;
            }
            PaasPrintTemplateEntity workOrderTemplate = new PaasPrintTemplateEntity();
            long now = DateTimeUtil.getInt();
            workOrderTemplate.setName("默认模板");
            workOrderTemplate.setCorpid(corpid);
            workOrderTemplate.setAppId(appId);
            workOrderTemplate.setMenuId(menuId);
            workOrderTemplate.setFormId(defaultFormId);
            workOrderTemplate.setCreatorId("0");
            workOrderTemplate.setAddTime(now);
            workOrderTemplate.setEnable(BasicConstant.ONE);
            workOrderTemplate.setUpdateTime(now);
            workOrderTemplate.setBusinessType(XbbRefTypeEnum.WORK_ORDER.getCode());
            workOrderTemplate.setHtml(defaultList.get(0).getHtml());
            workOrderTemplate.setConfigInfo(defaultList.get(0).getConfigInfo());
            paasPrintTemplateDao.insert(workOrderTemplate);
        } catch (Exception e) {
            LOG.error("InitWorkOrderDefaultTemplate.rollBackToDefaultPrintTemplates 初始化工单打印模板出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
    }
    /**
     * 批量添加表单
     * @author 吴峰
     * @date 2019/1/24 18:43
     * @param menuInitDTO
     * @return com.xbongbong.pro.menu.pojo.vo.MenuGroupAddBatchVO
     * @throws XbbException
     */
    public MenuFormAddBatchVO formAddBatch(MenuInitDTO menuInitDTO) throws XbbException {
        MenuFormAddBatchVO menuFormAddBatchVO;
        try {
            Long appId = menuInitDTO.getAppId();
            MenuFormAddBatchDTO crmFormAddBatchDTO = new MenuFormAddBatchDTO();
            BeanUtil.copyProperties(menuInitDTO, crmFormAddBatchDTO);
            crmFormAddBatchDTO.setAppId(appId);
            List<MenuFormAddDTO> groupMenuList = new ArrayList<>();
            for(WorkOrderMenuEnum menuEnum: WorkOrderMenuEnum.values()){
                if(StringUtil.isEmpty(menuEnum.getParent())){
                    MenuFormAddDTO menuGroupAddDTO = new MenuFormAddDTO();
                    BeanUtil.copyProperties(menuInitDTO, menuGroupAddDTO);
                    menuGroupAddDTO.setParentId(0L);
                    menuGroupAddDTO.setAppId(appId);
                    menuGroupAddDTO.setAlias(menuEnum.getAlias());
                    menuGroupAddDTO.setSaasMark(SaasMarkEnum.SAAS.getCode());
                    menuGroupAddDTO.setName(menuEnum.getName());
                    AccessLinkEnum accessLinkEnum = menuEnum.getAccessLinkEnum();
                    menuGroupAddDTO.setIcon(accessLinkEnum.getIcon());
                    menuGroupAddDTO.setColor(accessLinkEnum.getColor());
                    menuGroupAddDTO.setUrl(accessLinkEnum.getUrl());
                    menuGroupAddDTO.setMobileUrl(accessLinkEnum.getMobileUrl());
                    menuGroupAddDTO.setType(menuEnum.getType());
                    groupMenuList.add(menuGroupAddDTO);
                }
            }
            crmFormAddBatchDTO.setMenuList(groupMenuList);
            menuFormAddBatchVO = paasMenuService.addBatchFormMenu(crmFormAddBatchDTO);
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("InitWorkOrderMenuHelp.formAddBatch 批量添加分组出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return menuFormAddBatchVO;
    }

    /**
     * Description:
     * @param menuInitDTO
     * @param templateId
     * @return java.lang.Long
     * @throws XbbException XbbException
     * @author 魏荣杰
     * @date 2019/3/14 15:21
     * @since
     */
    private Long formAdd(MenuInitDTO menuInitDTO, Long templateId, Long menuId) throws XbbException {
        try {
            FormEntityAddDTO formEntityAddDTO = new FormEntityAddDTO();
            WorkOrderFormEntity workOrderFormEntity = new WorkOrderFormEntity();
            BeanUtil.copyProperties(formEntityAddDTO, workOrderFormEntity);
            workOrderFormEntity.setCorpid(menuInitDTO.getCorpid());
            workOrderFormEntity.setAppId(menuInitDTO.getAppId());
            workOrderFormEntity.setMenuId(menuId);
            workOrderFormEntity.setName(I18nMessageUtil.getMessage(I18nStringConstant.AFTER_SALE));

            workOrderFormEntity.setSummary(JSONObject.toJSONString(getWorkOrderDefaultSummary(XbbRefTypeEnum.WORK_ORDER.getCode())));
            workOrderFormEntity.setLabels(JSONObject.toJSONString(getWorkOrderDefaultLabel(XbbRefTypeEnum.WORK_ORDER.getCode())));
            workOrderFormEntity.setAssociationList(JSONObject.toJSONString(formEntityAddDTO.getAssociationList()));
            workOrderFormEntity.setBusinessRules(formEntityAddDTO.getBusinessRules());
            workOrderFormEntity.setCoOpPerms(JSONObject.toJSONString(formEntityAddDTO.getCoOpPerms()));
            workOrderFormEntity.setCustomTitle(JSONObject.toJSONString(getWorkOrderDefaultTitle(XbbRefTypeEnum.WORK_ORDER.getCode())));
            workOrderFormEntity.setCreatorId(menuInitDTO.getUserId());
            workOrderFormEntity.setTemplateId(templateId);
            Long now = DateTimeUtil.getInt();
            workOrderFormEntity.setAddTime(now);
            workOrderFormEntity.setUpdateTime(now);
            workOrderFormEntity.setDel(0);
            workOrderFormModel.insert(workOrderFormEntity);
            return workOrderFormEntity.getId();
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("InitWorkOrderHelp.formAdd添加表单设计信息出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
    }

    /**
     * Description:
     * @param menuInitDTO
     * @param formId
     * @return void
     * @throws
     * @author 魏荣杰
     * @date 2019/3/14 16:35
     * @since v1.0
     */
    private void formExplainAdd(MenuInitDTO menuInitDTO, Long formId, Long menuId) throws XbbException {
        try {
            WorkOrderExplainEntity workOrderExplainEntity = new WorkOrderExplainEntity();
            workOrderExplainEntity.setCorpid(menuInitDTO.getCorpid());
            workOrderExplainEntity.setAppId(menuInitDTO.getAppId());
            workOrderExplainEntity.setMenuId(menuId);
            workOrderExplainEntity.setFormId(formId);
            List<FieldAttrEntity> explains = new ArrayList<>();
            if (!InitExplainsHelper.EMPTY_EXPLAIN.contains(XbbRefTypeEnum.WORK_ORDER.getCode())) {
                FundSetTransitionPojo fundSetTransitionPojo = new FundSetTransitionPojo(menuInitDTO.getCorpid());
                explains = InitExplainsHelper.initFieldAttrEntity(XbbRefTypeEnum.WORK_ORDER.getAlias(), menuInitDTO.getProductForm(), fundSetTransitionPojo, 0);
            }
            workOrderExplainEntity.setExplains(JSON.toJSONString(explains));
            workOrderExplainEntity.setCreatorId(menuInitDTO.getUserId());
            workOrderExplainEntity.setDel(0);
            workOrderExplainModel.insert(workOrderExplainEntity);
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("InitWorkOrderHelp.formExplainAdd添加表单解释信息出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }

    }

    /**
     * 获取默认标题
     *
     * @param businessType 业务类型
     * @author long.rao
     * @date 2019-07-12 14:27
     */
    public List<FormTitlePoJo> getWorkOrderDefaultTitle(Integer businessType) {
        List<Object> titleAttrList;
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
        switch (xbbRefTypeEnum) {
            case WORK_ORDER:
                titleAttrList = WorkOrderEnum.getTitleAttrList();
                break;
            default:
                titleAttrList = new ArrayList<>();
                break;
        }
        List<FormTitlePoJo> formTitlePoJoList = new ArrayList<>();
        for (Object object : titleAttrList) {
            if (Objects.nonNull(object)) {
                Object attr;
                Object attrName;
                if (object instanceof JSONObject) {
                    JSONObject itemObj = (JSONObject) object;
                    attr = itemObj.get("attr");
                    attrName = itemObj.get("attrName");
                } else {
                    attr = ReflectHelper.valueGet(object, "attr");
                    attrName = ReflectHelper.valueGet(object, "attrName");
                }
                FormTitlePoJo formTitlePoJo = new FormTitlePoJo();
                if (Objects.nonNull(attr)) {
                    ReflectHelper.valueSet(formTitlePoJo, "attr", attr);
                }
                if (Objects.nonNull(attrName)) {
                    ReflectHelper.valueSet(formTitlePoJo, "attrName", attrName);
                }
                formTitlePoJoList.add(formTitlePoJo);
            }
        }
        return formTitlePoJoList;
    }

    /**
     * 获取工单默认摘要
     *
     * @param businessType 业务类型
     * @author long.rao
     * @date 2019-07-12 14:29
     */
    public List<SummaryDataPoJo> getWorkOrderDefaultSummary(Integer businessType) {
        List<Object> summaryList;
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
        switch (xbbRefTypeEnum) {
            case WORK_ORDER:
                summaryList = WorkOrderEnum.getSummaryAttrList();
                break;
            default:
                summaryList = new ArrayList<>();
                break;
        }
        List<SummaryDataPoJo> summaryDataPoJoList = new ArrayList<>();
        for (Object object : summaryList) {
            if (Objects.nonNull(object)) {
                Object attr;
                Object attrName;
                Object fieldType;
                if (object instanceof JSONObject) {
                    JSONObject itemObj = (JSONObject) object;
                    attr = itemObj.get("attr");
                    attrName = itemObj.get("attrName");
                    fieldType = itemObj.get("fieldType");
                } else {
                    attr = ReflectHelper.valueGet(object, "attr");
                    attrName = ReflectHelper.valueGet(object, "attrName");
                    fieldType = ReflectHelper.valueGet(object, "fieldType");
                }
                SummaryDataPoJo summaryDataPoJo = new SummaryDataPoJo();
                if (Objects.nonNull(attr)) {
                    ReflectHelper.valueSet(summaryDataPoJo, "attr", attr);
                }
                if (Objects.nonNull(attrName)) {
                    ReflectHelper.valueSet(summaryDataPoJo, "attrName", attrName);
                }
                if (Objects.nonNull(fieldType)) {
                    ReflectHelper.valueSet(summaryDataPoJo, "fieldType", fieldType);
                }
                summaryDataPoJoList.add(summaryDataPoJo);
            }
        }
        return summaryDataPoJoList;
    }

    /**
     * 获取工单默认标签
     *
     * @param businessType 业务类型
     * @author long.rao
     * @date 2019-07-12 14:32
     */
    public List<SummaryDataPoJo> getWorkOrderDefaultLabel(Integer businessType) {
        List<Object> labelAttrList;
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
        switch (xbbRefTypeEnum) {
            default:
                labelAttrList = new ArrayList<>();
                break;
        }
        List<SummaryDataPoJo> summaryDataPoJoList = new ArrayList<>();
        for (Object object : labelAttrList) {
            if (Objects.nonNull(object)) {
                Object attr;
                Object attrName;
                Object fieldType;
                if (object instanceof JSONObject) {
                    JSONObject itemObj = (JSONObject) object;
                    attr = itemObj.get("attr");
                    attrName = itemObj.get("attrName");
                    fieldType = itemObj.get("fieldType");
                } else {
                    attr = ReflectHelper.valueGet(object, "attr");
                    attrName = ReflectHelper.valueGet(object, "attrName");
                    fieldType = ReflectHelper.valueGet(object, "fieldType");
                }
                SummaryDataPoJo summaryDataPoJo = new SummaryDataPoJo();
                if (Objects.nonNull(attr)) {
                    ReflectHelper.valueSet(summaryDataPoJo, "attr", attr);
                }
                if (Objects.nonNull(attrName)) {
                    ReflectHelper.valueSet(summaryDataPoJo, "attrName", attrName);
                }
                if (Objects.nonNull(fieldType)) {
                    ReflectHelper.valueSet(summaryDataPoJo, "fieldType", fieldType);
                }
                summaryDataPoJoList.add(summaryDataPoJo);
            }
        }
        return summaryDataPoJoList;
    }
}
